from sqlalchemy.orm import Session
from typing import List, Optional
from sqlalchemy.sql.expression import func

from app.models.question import Question
from app.schemas.question import QuestionCreate, QuestionUpdate  # Assuming QuestionUpdate schema exists or is needed


def get_question(db: Session, question_id: int) -> Optional[Question]:
    """获取单个题目"""
    return db.query(Question).filter(Question.id == question_id).first()

def get_questions(db: Session, skip: int = 0, limit: int = 100) -> List[Question]:
    """获取题目列表（带分页）"""
    return db.query(Question).offset(skip).limit(limit).all()

def create_question(db: Session, question: QuestionCreate) -> Question:
    """创建新题目"""
    db_question = Question(**question.dict())
    db.add(db_question)
    db.commit()
    db.refresh(db_question)
    return db_question

def get_random_questions(
    db: Session,
    subject: str,
    model: str,
    limit: int = 100
):
    return db.query(Question)\
        .filter(Question.subject == subject)\
        .filter(Question.model == model)\
        .order_by(func.random())\
        .limit(limit)\
        .all()

def get_questions_by_subject_and_model(
    db: Session, 
    subject: str, 
    model: str, 
    skip: int = 0, 
    limit: int = 100
) -> List[Question]:
    """根据科目和车型获取题目列表"""
    return db.query(Question)\
        .filter(Question.subject == subject)\
        .filter(Question.model == model)\
        .offset(skip)\
        .limit(limit)\
        .all()

def get_question_by_id(db: Session, question_id: int) -> Optional[Question]:
    """根据ID获取题目"""
    return db.query(Question).filter(Question.id == question_id).first()

# Optional: Add update and delete functions if needed
# def update_question(db: Session, question_id: int, question_update: QuestionUpdate) -> Optional[Question]:
#     """更新题目"""
#     db_question = get_question(db, question_id)
#     if db_question:
#         update_data = question_update.dict(exclude_unset=True)
#         for key, value in update_data.items():
#             setattr(db_question, key, value)
#         db.commit()
#         db.refresh(db_question)
#     return db_question
#
# def delete_question(db: Session, question_id: int) -> Optional[Question]:
#     """删除题目"""
#     db_question = get_question(db, question_id)
#     if db_question:
#         db.delete(db_question)
#         db.commit()
#     return db_question 